package com.qf.controller;

import com.qf.pojo.Address;
import com.qf.pojo.Cart;
import com.qf.pojo.Orders;
import com.qf.pojo.User;
import com.qf.service.AddressService;
import com.qf.service.CartService;
import com.qf.service.OrderService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.CartServiceImpl;
import com.qf.service.impl.OrderServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 消费者订单管理
 * @author 千锋健哥
 */
@WebServlet("/order")
public class OrderController extends BaseController {

    /**
     * 进入订单预览页面
     * @param request
     * @param response
     * @return
     */
    public String preView(HttpServletRequest request, HttpServletResponse response) {
        //1. 从session会话中获取当前登录用户对象
        User user = (User) request.getSession().getAttribute("loginUser");

        //2. 判断如果获取不到, 那么说明用户未登录或者登录超时, 跳转到登录页面重新登录
        if (user == null) {
            return "redirect:/login.jsp";
        }

        //3. 根据用户名, 获取这个用户的地址列表
        AddressService addressService = new AddressServiceImpl();
        List<Address> addressList = addressService.findList(user.getId());

        //4. 根据用户名, 获取这个用户的购物车中购物项列表
        CartService cartService = new CartServiceImpl();
        List<Cart> cartList = cartService.findCartByUid(user.getId());

        //5. 将数据放入request域中
        request.setAttribute("addressList", addressList);
        request.setAttribute("cartList", cartList);

        //6. 跳转到订单预览页面展示
        return "forward:/order.jsp";
    }

    /**
     * 提交保存订单
     * @param request
     * @param response
     * @return
     */
    public String create(HttpServletRequest request, HttpServletResponse response) {
        //1. 从session会话中获取当前登录用户对象
        User user = (User) request.getSession().getAttribute("loginUser");

        //2. 判断如果获取不到, 那么说明用户未登录或者登录超时, 跳转到登录页面重新登录
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //3. 获取用户收货地址
        String addressId = request.getParameter("aid");

        //3. 根据用户id, 调用service下订单
        OrderService orderService = new OrderServiceImpl();
        orderService.create(user.getId(), Integer.parseInt(addressId));

        //4. 根据用户id, 调用service查询订单列表数据(包含订单, 订单详情列表, 收货地址)
        List<Orders> orderList = orderService.findOrderList(user.getId());

        //5. 将这些数据放入request域中
        request.setAttribute("ordersList", orderList);

        //6. 跳转到订单列表页面
        return "forward:/orderList.jsp";
    }

}
